<template>
  <div>
    <!-- 顶部导航栏 -->
    <!-- <el-header class="custom-header">
      <div class="header-left">
        <span class="logo-title">作物标准象与象差知识库系统</span>
      </div>
    
    </el-header> -->
    
    <!-- 分类导航 -->
    <div>
      <el-menu 
        :default-active="activeIndex" 
        class="custom-menu" 
        mode="horizontal"
        @select="handleSelect">
        <el-menu-item index="1">首页</el-menu-item>
        <el-menu-item index="2">标准象百科</el-menu-item>
        <el-menu-item index="3">象差百科</el-menu-item>
        <el-menu-item index="4">知识检索</el-menu-item>
        <el-menu-item index="5">问答专区</el-menu-item>
      </el-menu>
    </div>
    
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="headline">标准象与象差知识库系统上线了</div>
      
      <div class="search-bar">
        <el-input 
          v-model="searchKeyword" 
          placeholder="请输入关键词"
          class="search-input"
          clearable>
          <template #append>
            <el-button type="primary" @click="onSearch" style="font-size:20px;color:#409EFF">搜索</el-button>
          </template>
        </el-input>
      </div>
      
      <div class="hot-words">
        热门搜索：
        <el-link type="primary" @click="setKeyword('小麦赤霉病')">小麦赤霉病</el-link>
        <el-link type="primary" @click="setKeyword('玉米褐斑病')">玉米褐斑病</el-link>
      </div>
    </div>
    
    <!-- 🔥 数据统计 - 动态数据 + 加载状态 -->
    <div class="stats-section" v-loading="statsLoading">
      <div 
        v-for="item in stats" 
        :key="item.label" 
        class="stats-card"
        @click="handleStatsClick(item.label)">
        <div class="circle-number">{{ item.count }}</div>
        <div class="label">{{ item.label }}</div>
      </div>
    </div>
    
    <!-- 🔥 象差百科 -->
    <div class="pest-container">
      <div class="header-section">
        <h2 class="title">象差百科</h2>
        <el-button type="primary" class="more-btn" @click="handleSelect(3)">获取更多</el-button>
      </div>
      
      <div class="pest-cards">
        <el-card 
          v-for="(pest, index) in pests" 
          :key="index"
          class="pest-card" 
          shadow="hover"
          @click="handlePestCardClick(pest)">
          <div class="card-content">
            <div class="pest-image">
              <img :src="pest.image" :alt="pest.name">
            </div>
            <div class="pest-info">
              <h3 class="pest-name">{{ pest.name }}</h3>
              <p class="pest-description">{{ pest.description }}</p>
            </div>
          </div>
        </el-card>
      </div>
    </div>
    
    <!-- 问答专区 -->
    <div class="pest-container">
      <div class="header-section">
        <h2 class="title">问答专区</h2>
        <el-button type="primary" class="more-btn" @click="handleSelect(5)">获取更多</el-button>
      </div>
      
      <div class="qa-list" @click="handleSelect(5)">
        <div 
          v-for="(question, index) in questions" 
          :key="index"
          class="qa-item">
          <div class="reward-tag">悬赏{{ question.reward }}分</div>
          <div class="question-content">
            <h3>{{ question.title }}</h3>
            <div class="question-meta">
              <span><i class="far fa-clock"></i> {{ question.time }}</span>
              <span><i class="fas fa-user"></i> {{ question.author }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElHeader, ElMenu, ElMenuItem, ElIcon, ElSelect, ElOption, ElInput, ElButton, ElLink, ElCard, ElMessage } from 'element-plus';
import { User } from '@element-plus/icons-vue';
import { useRouter } from 'vue-router';

// 🔥 导入统计数据API
import { getHomeStatistics } from '@/api/agriculture/guo/knowledge/statistics';

const router = useRouter();

// 响应式变量
const activeIndex = ref('1');
const searchType = ref('search');
const searchKeyword = ref('');
const statsLoading = ref(false); // 🔥 统计数据加载状态

// 🔥 统计数据 - 改为响应式，支持动态更新
const stats = ref([
  { label: '标准象', count: 0 },
  { label: '病害', count: 0 },
  { label: '虫害', count: 0 },
  { label: '非生物胁迫', count: 0 }
]);

const routerList = [  
  "",
  "CropIndex",           // 首页
  "CropVarietyFront",      // 作物品种
  "CropDiseasePest", // 病虫害
  "CropGraph",           // 图谱
  "QA"               // 问答
];

// 病虫害数据
const pests = ref([
  {
    name: '小麦赤霉病',
    description: '小麦赤霉病又称烂穗病、麦秸枯、烂麦头、红麦头、红头瘴，是由多种镰刀菌侵染所引起的、发生在小麦上的病害。从苗期到穗期均可发生，引起苗腐、茎基腐、秆腐和穗腐，以腐危害最大。湿度大时，病部均可见粉红色霉层。小麦受害后千综合粒重降低，发芽率下降，发芽势减弱，出粉率低，面粉质量差，色泽灰暗，商品价值降低。病麦含有致呕毒素和类性激素述等毒素，人畜食后可引起急性中毒。病麦粒中含有脱氧雪腐镰刀菌烯醇、玉米赤霉烯酮等毒素，还会导致怀孕母中毒后流产',
    image: 'https://zjjcmspublicnew.oss-cn-hangzhou-zwynet-d01-a.internet.cloud.zj.gov.cn/cms_files/jcms1/web3628/site/picture/-1/211229093510188871.jpg'
  },
  {
    name: '稻曲病',
    description: '稻曲病又称伪黑穗病、绿黑穗病，是由稻绿核菌引起的、发生在水稻上的一种病害。该病仅在穗部发生，为害稻穗上的部分谷粒。其先在颖壳的合缝处露出淡黄绿色的小菌块，逐膨大，最后包裹全颖壳，为墨绿色或橄榄色，最后开裂，布满墨绿色粉末。[1]稻曲病为水稻主要病害，在世界水稻产区内均-般发病率为3-5%，严重的达30%以上，减产可达有分布，20-30%。[2]稻曲病采用农药防治和药剂防治两种方式结合病品种进行种植，避免病谷留种。',
    image: 'https://n.sinaimg.cn/sinacn09/223/w640h383/20180513/5dca-hamfahx4062502.jpg'
  }
]);

// 问答数据
const questions = ref([
  { 
    title: '玉米缺氮素表现出什么症状？如何矫正', 
    reward: 50, 
    time: '1小时前', 
    author: '玉米种植户' 
  },
  { 
    title: '怎样种植甜玉米', 
    reward: 30, 
    time: '3小时前', 
    author: '新农人' 
  },
  { 
    title: '小麦叶面鳞酮有什么作用？', 
    reward: 50, 
    time: '5小时前', 
    author: '小麦研究员' 
  },
  { 
    title: '影响小麦品质的因素有哪些？', 
    reward: 50, 
    time: '昨天', 
    author: '品质分析师' 
  },
  { 
    title: '如何选用水肥品种', 
    reward: 20, 
    time: '昨天', 
    author: '水肥管理' 
  }
]);

// 🔥 新增：加载统计数据
const loadStatisticsData = async () => {
  try {
    statsLoading.value = true;
    console.log('🔍 开始加载首页统计数据...');
    
    const response = await getHomeStatistics();
    console.log('📊 统计数据响应:', response);
    
    if (response.code === 200 && response.data) {
      const data = response.data;
      
      // 🔥 更新统计数据
      stats.value = [
        { 
          label: '标准象', 
          count: data.varietyCount || 0,
          description: '作物品种总数'
        },
        { 
          label: '病害', 
          count: data.diseaseCount || 0,
          description: '病害种类总数'
        },
        { 
          label: '虫害', 
          count: data.pestCount || 0,
          description: '虫害种类总数'
        },
        { 
          label: '非生物胁迫', 
          count: data.stressCount || 0,
          description: '非生物胁迫总数'
        }
      ];
      
      console.log('✅ 统计数据更新成功:', stats.value);
      ElMessage.success('统计数据加载成功');
      
    } else {
      console.error('❌ 获取统计数据失败:', response.msg);
      ElMessage.warning('统计数据加载失败，显示默认数据');
      
      // 🔥 使用默认数据
      stats.value = [
        { label: '标准象', count: 152 },
        { label: '病害', count: 87 },
        { label: '虫害', count: 64 },
        { label: '非生物胁迫', count: 39 }
      ];
    }
  } catch (error) {
    console.error('💥 加载统计数据出错:', error);
    ElMessage.error('统计数据加载失败，请检查网络连接');
    
    // 🔥 出错时使用默认数据
    stats.value = [
      { label: '标准象', count: 152 },
      { label: '病害', count: 87 },
      { label: '虫害', count: 64 },
      { label: '非生物胁迫', count: 39 }
    ];
  } finally {
    statsLoading.value = false;
  }
};

// 🔥 统计卡片点击处理（保持原有逻辑）
const handleStatsClick = (label) => {
  console.log('点击统计卡片:', label);
  
  if (label === '标准象') {
    // 跳转到标准象百科
    router.push({ name: 'CropVarietyFront' });
    ElMessage.success('正在跳转到标准象百科...');
  } else if (label === '病害' || label === '虫害' || label === '非生物胁迫') {
    // 跳转到象差百科
    router.push({ name: 'CropDiseasePest' });
    ElMessage.success(`正在跳转到象差百科...`);
  }
};

// 🔥 病虫害卡片点击处理（保持原有逻辑）
const handlePestCardClick = (pest) => {
  console.log('点击病虫害卡片:', pest.name);
  
  // 跳转到象差百科并搜索对应的病虫害
  router.push({ 
    name: 'CropDiseasePest',
    query: {
      search: pest.name
    }
  });
  ElMessage.success(`正在查看${pest.name}详情...`);
};

const handleSelect = (key) => { 
  activeIndex.value = key;
  const routeName = routerList[key];
  console.log('激活的导航项:', key, routeName);
  router.push({ name: routeName }); 
};

const onSearch = () => { 
  console.log('关键词:', searchKeyword.value);
  router.push({ 
    name: 'CropGraph',
    query: { searchKeyword: searchKeyword.value }
  }); 
};

const setKeyword = (word) => {
  searchKeyword.value = word;
  onSearch();
};

// 🔥 页面加载时获取统计数据
onMounted(() => {
  console.log('🚀 首页组件已加载，开始获取统计数据...');
  loadStatisticsData();
});
</script>

<style scoped>
/* 🔥 保持原有样式，新增加载状态优化 */

/* 顶部导航栏 */
.custom-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background: linear-gradient(90deg, #1bbc9b, #17c2e6);
  color: #fff;
  font-size: 18px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.logo-title {
  font-weight: bold;
  font-size: 22px;
}

.header-right {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
}

/* 分类导航 */
.custom-menu {
  border-bottom: 1px solid #e0e0e0;
  padding: 0 30px;
  font-size: 16px;
}

/* 搜索区域 */
.search-section {
  text-align: center;
  padding: 30px 20px;
  background-color: #f9f9f9;
}

.headline {
  font-size: 22px;
  font-weight: bold;
  margin-bottom: 20px;
}

.search-bar {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

.search-select {
  width: 120px;
}

.search-input {
  width: 60vw;
  height: 50px;
}

.hot-words {
  font-size: 14px;
  color: #666;
}

.hot-words .el-link {
  margin-left: 10px;
}

/* 🔥 统计数据 - 添加加载状态优化 */
.stats-section {
  display: flex;
  justify-content: center;
  gap: 10vw;
  flex-wrap: wrap;
  padding: 20px 0;
  background-color: #fff;
  position: relative;
  min-height: 180px; /* 🔥 确保加载状态有足够高度 */
}

.stats-card {
  width: 140px;
  height: 140px;
  background-color: #f5f7fa;
  border-radius: 16px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.05);
  transition: all 0.3s;
  cursor: pointer;
  opacity: 1; /* 🔥 确保卡片可见 */
}

.stats-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 14px rgba(0, 0, 0, 0.08);
  background-color: #e8f4f8;
}

.stats-card:active {
  transform: translateY(-2px);
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.circle-number {
  width: 64px;
  height: 64px;
  line-height: 64px;
  border-radius: 50%;
  background-color: #409EFF;
  color: #fff;
  font-size: 20px;
  font-weight: bold;
  text-align: center;
  margin-bottom: 12px;
  transition: all 0.3s;
}

.stats-card:hover .circle-number {
  background-color: #42b883;
  transform: scale(1.05);
}

.label {
  font-size: 16px;
  color: #333;
  transition: all 0.3s;
}

.stats-card:hover .label {
  color: #42b883;
  font-weight: 600;
}

/* 🔥 加载状态时的卡片样式 */
.stats-section[v-loading] .stats-card {
  pointer-events: none;
  opacity: 0.6;
}

/* 内容区域 */
.pest-container {
  min-width: 900px;
  margin: 0 auto;
  padding: 10px 100px;
  box-sizing: border-box;
  font-family: "Helvetica Neue", Helvetica, "PingFang SC", Arial, sans-serif;
}

.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 25px;
  padding-bottom: 15px;
  border-bottom: 1px solid #eee;
}

.title {
  font-size: 24px;
  color: #303133;
  margin: 0;
}

.more-btn {
  background-color: #2e7d32;
  border-color: #2e7d32;
  color: white;
  font-weight: bold;
}

.more-btn:hover {
  background-color: #4caf50;
  border-color: #4caf50;
}

.pest-cards {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 25px;
}

.pest-card {
  border-radius: 8px;
  border: none;
  transition: transform 0.3s;
  cursor: pointer;
}

.pest-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 16px rgba(46, 125, 50, 0.1) !important;
}

.card-content {
  display: flex;
  padding: 15px;
}

.pest-image {
  max-width: 15vw;
  width: 230px;
  height: 300px;
  margin-right: 20px;
  background-color: #f5f5f5;
  border-radius: 4px;
  overflow: hidden;
}

.pest-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.pest-info {
  flex: 1;
}

.pest-name {
  font-size: 18px;
  font-weight: bold;
  color: #303133;
  margin-top: 0;
  margin-bottom: 15px;
}

.pest-description {
  font-size: 14px;
  line-height: 1.6;
  color: #606266;
  margin: 0;
}

/* 问答区域 */
.qa-list {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.qa-item {
  display: flex;
  padding: 15px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  transition: all 0.3s;
}

.qa-item:hover {
  border-color: #4caf50;
  background: rgba(46, 125, 50, 0.03);
}

.reward-tag {
  min-width: 80px;
  background: #FFC107;
  color: #333;
  border-radius: 4px;
  font-weight: 700;
  padding: 5px 10px;
  text-align: center;
  font-size: 0.9rem;
  height: fit-content;
}

.question-content {
  flex: 1;
  padding: 0 15px;
}

.question-content h3 {
  font-size: 1.1rem;
  font-weight: 600;
  margin: 0 0 8px 0;
  color: #303133;
}

.question-meta {
  display: flex;
  color: #909399;
  font-size: 0.85rem;
  gap: 15px;
}

/* 🔥 响应式设计优化 */
@media (max-width: 768px) {
  .stats-section {
    gap: 5vw;
    padding: 15px;
    min-height: 160px; /* 🔥 移动端调整高度 */
  }
  
  .stats-card {
    width: 120px;
    height: 120px;
  }
  
  .circle-number {
    width: 50px;
    height: 50px;
    line-height: 50px;
    font-size: 16px;
  }
  
  .label {
    font-size: 14px;
  }
}
</style>